<template>
  <div v-if="!item.hidden">
    <template
      v-if="hasOneShowingChild(item.children, item) &&
        (!onlyOneChild.children || onlyOneChild.noShowingChildren) &&
        !item.alwaysShow"
    >
      <app-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)">
        <el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown':!isNest}">
          <el-icon v-if="onlyOneChild.meta.icon" class="menu-icon">
            <component :is="getIconComponent(onlyOneChild.meta.icon)" />
          </el-icon>
          <template #title>
            <span>{{ onlyOneChild.meta.title }}</span>
          </template>
        </el-menu-item>
      </app-link>
    </template>

    <el-sub-menu v-else ref="subMenu" :index="resolvePath(item.path)" teleported>
      <template #title>
        <el-icon v-if="item.meta && item.meta.icon" class="menu-icon">
          <component :is="getIconComponent(item.meta.icon)" />
        </el-icon>
        <span>{{ item.meta && item.meta.title }}</span>
      </template>
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.path)"
        class="nest-menu"
      />
    </el-sub-menu>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// import path from 'path-browserify'
import * as ElementPlusIcons from '@element-plus/icons-vue'

import AppLink from './Link.vue'
import type { AppRouteRecordRaw } from '@/types/system'

interface Props {
  item: AppRouteRecordRaw
  isNest?: boolean
  basePath?: string
}

const props = withDefaults(defineProps<Props>(), {
  isNest: false,
  basePath: ''
})

const onlyOneChild = ref<AppRouteRecordRaw>({} as AppRouteRecordRaw)

// 简单的路径解析函数
function pathResolve(basePath: string, relativePath: string): string {
  if (!relativePath) return basePath
  if (relativePath.startsWith('/')) return relativePath
  if (isExternalLink(relativePath)) return relativePath
  if (isExternalLink(basePath)) return basePath

  const base = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath
  const rel = relativePath.startsWith('/') ? relativePath : '/' + relativePath
  return base + rel
}

// 是否只显示一个子菜单
function hasOneShowingChild(children: AppRouteRecordRaw[] = [], parent: AppRouteRecordRaw): boolean {
  const showingChildren = children.filter(item => {
    if (item.hidden) {
      return false
    } else {
      // 设置临时的父路由，用于判断当前路由
      onlyOneChild.value = item
      return true
    }
  })

  // 当只有一个子路由，该子路由默认不显示
  if (showingChildren.length === 1) {
    return true
  }

  // 如果没有子路由显示，显示父路由
  if (showingChildren.length === 0) {
    onlyOneChild.value = { ...parent, path: '', noShowingChildren: true } as AppRouteRecordRaw
    return true
  }

  return false
}

// 解析路径
function resolvePath(routePath: string): string {
  if (isExternalLink(routePath)) {
    return routePath
  }
  if (isExternalLink(props.basePath)) {
    return props.basePath
  }
  return pathResolve(props.basePath, routePath)
}

// 是否是外部链接
function isExternalLink(path: string): boolean {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// 获取图标组件
function getIconComponent(iconName: string | undefined) {
  if (!iconName) return null

  // 调试：输出图标信息
  // if (import.meta.env.MODE !== 'production') {
  //   console.log('🎨 SidebarItem 图标调试:', {
  //     iconName,
  //     available: !!ElementPlusIcons[iconName as keyof typeof ElementPlusIcons],
  //     item: props.item.name || props.item.path,
  //     meta: props.item.meta
  //   })
  // }

  return ElementPlusIcons[iconName as keyof typeof ElementPlusIcons] || null
}
</script>

<style lang="scss" scoped>
.menu-icon {
  margin-right: 8px;
  min-width: 16px;
  font-size: 16px;
  color: inherit;
}

// 确保图标在菜单项中垂直居中
.el-menu-item, .el-sub-menu__title {
  .menu-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
